#Region " Imports "

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Text.RegularExpressions
Imports BlazeApps.Library.Options
Imports BA.Mail
Imports System.Configuration.ConfigurationManager
Imports System.Net.Mail
Imports System.Text
Imports BlazeApps.Library.Messaging

#End Region

Public Class Helpers
    Inherits WebControlBase

#Region " Declarations "

    Private PageStartTime As DateTime = DateTime.Now
    Private PU As New ProfileUtility

#End Region

#Region " Site Helpers "

    Protected Function FormatDisplayLength(ByVal Value As String, ByVal MaxLength As Integer, ByVal DisplayLength As Integer) As String

        If Value.Length > MaxLength Then
            Return String.Format("{0}...", Left(Value, DisplayLength))
        Else
            Return Value
        End If

    End Function

    Protected Function FormatReportDisplayLength(ByVal Value As String, ByVal MaxLength As Integer, ByVal DisplayLength As Integer) As String

        If Value.IndexOf(" ", 0) >= 25 Then
            If Value.Length > MaxLength Then
				Return String.Format("{0}...", Left(Value, DisplayLength))
			Else
				Return Value
			End If
        Else
            Return Value
        End If

    End Function

    Protected Function FormatPublicRank() As String
        Return String.Format("<b>{0}</b>", Resources.Resource.PublicRank)
    End Function

    Protected Function FormatPrivateRank() As String
        Return String.Format("<b>{0}</b>", Resources.Resource.PrivateRank)
    End Function

    Protected Function FormatAccessType(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.AccessTypeRequired, ItemValue)
    End Function

    Protected Function FormatAccessLevel(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.LevelRequired, ItemValue)
    End Function

    Protected Function FormatCreateDate(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.Created, Format(Convert.ToDateTime(ItemValue), Resources.Resource.DateFormat).ToString)
    End Function

    Protected Function FormatEditDate(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.Edited, Format(Convert.ToDateTime(ItemValue), Resources.Resource.DateFormat).ToString)
    End Function

    Protected Function FormatLongCreateDate(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.Created, Format(Convert.ToDateTime(ItemValue), Resources.Resource.DateTimeFormat))
    End Function

    Protected Function FormatLongEditDate(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.Edited, Format(Convert.ToDateTime(ItemValue), Resources.Resource.DateTimeFormat))
    End Function

    Protected Function FormatViews(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b>  {1:#,###}", Resources.Resource.Views, ItemValue)
    End Function

    Protected Function FormatComments(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> ({1:#,###})", Resources.Resource.Comments, ItemValue)
    End Function

    Protected Function FormatPostCount(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1:#,###}", Resources.Resource.Posts, ItemValue)
    End Function

    Protected Function FormatInteger(ByVal ItemValue As String) As String
        Return String.Format("{0:#,###}", ItemValue)
    End Function

    Protected Function FormatEventDate(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.EventDate, Format(Convert.ToDateTime(ItemValue), Resources.Resource.DateFormat).ToString)
    End Function

    Protected Function FormatClosesOnDate(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.ClosesOn, Format(Convert.ToDateTime(ItemValue), Resources.Resource.DateFormat).ToString)
    End Function

    Protected Function FormatTotalVotes(ByVal ItemValue As String) As String
        Return String.Format("<b>{0}</b> {1}", Resources.Resource.TotalVotes, ItemValue)
    End Function

    Public Function AddPageTimer(ByVal message As String) As String
        Dim Time As Double = (DateTime.Now - PageStartTime).TotalSeconds
        Dim TimeDisplay As StringBuilder = New StringBuilder

        SyncLock TimeDisplay
            TimeDisplay.AppendFormat("{0} {1:00.000} {2}", message, Time, Resources.Resource.TimeSeconds)
        End SyncLock

        Return TimeDisplay.ToString

    End Function

    Protected Function SetHTMLReturn(ByVal Input As String) As String

        Return Replace(Input, Chr(13) & Chr(10), "<br />")

    End Function

    Protected Function SetCarriageReturn(ByVal Input As String) As String

        Return Replace(Input, "<br />", Chr(13) & Chr(10))

    End Function

    ''' <summary>
    ''' Used to replace HTML tags within a string
    ''' </summary>
    ''' <param name="Data">The HTML data</param>
    ''' <returns>A string with the HTML tags removed</returns>
    ''' <remarks></remarks>
    ''' 
    Protected Function RemoveHTMLTags(ByVal Data As String) As String
        Dim Pos1 As Integer
        Dim Pos2 As Integer
        Dim Pos3 As Integer
        Dim Result As String = String.Empty
        Dim TagName As String = String.Empty
        Dim Remove As Boolean
        Dim SearchForBlock As Boolean
        Dim HTMLTagList As New StringBuilder
        Dim HTMLBlockTagList As New StringBuilder

        'Section for literal replacements before the HTML coding is removed
        Data = Replace(Data, "<BR>", Chr(13) & Chr(10)) 'replace the BR's with carriage returns
        Data = Replace(Data, "<BR />", Chr(13) & Chr(10)) 'replace the BR's with carriage returns
        Data = Replace(Data, "<br>", Chr(13) & Chr(10)) 'replace the BR's with carriage returns
        Data = Replace(Data, "<br />", Chr(13) & Chr(10)) 'replace the BR's with carriage returns
        Data = Replace(Data, "&nbsp;", Chr(32)) 'replace the &nbsp;'s with spaces

        'Build the list of items to strip from the HTML code
        HTMLTagList.Append(";!--;!DOCTYPE;A;ACRONYM;ADDRESS;APPLET;AREA;B;BASE;BASEFONT;")
        HTMLTagList.Append("BGSOUND;BIG;BLOCKQUOTE;BODY;BUTTON;CAPTION;CENTER;CITE;CODE;")
        HTMLTagList.Append("COL;COLGROUP;COMMENT;DD;DEL;DFN;DIR;DIV;DL;DT;EM;EMBED;FIELDSET;")
        HTMLTagList.Append("FONT;FORM;FRAME;FRAMESET;HEAD;H1;H2;H3;H4;H5;H6;HR;HTML;I;IFRAME;IMG;")
        HTMLTagList.Append("INPUT;INS;ISINDEX;KBD;LABEL;LAYER;LAGEND;LI;LINK;LISTING;MAP;MARQUEE;")
        HTMLTagList.Append("MENU;META;NOBR;NOFRAMES;NOSCRIPT;OBJECT;OL;OPTION;P;PARAM;PLAINTEXT;")
        HTMLTagList.Append("PRE;Q;S;SAMP;SCRIPT;SELECT;SMALL;SPAN;STRIKE;STRONG;STYLE;SUB;SUP;")
        HTMLTagList.Append("TABLE;TBODY;TD;TEXTAREA;TFOOT;TH;THEAD;TITLE;TR;TT;U;UL;VAR;WBR;XMP;")

        HTMLBlockTagList.Append(";APPLET;EMBED;FRAMESET;HEAD;NOFRAMES;NOSCRIPT;OBJECT;SCRIPT;STYLE;")

        Pos1 = InStr(Data, "<")
        Do While Pos1 > 0
            Pos2 = InStr(Pos1 + 1, Data, ">")
            If Pos2 > 0 Then
                TagName = Mid(Data, Pos1 + 1, Pos2 - Pos1 - 1)
                TagName = Replace(Replace(TagName, vbCr, " "), vbLf, " ")

                Pos3 = InStr(TagName, " ")
                If Pos3 > 0 Then
                    TagName = Left(TagName, Pos3 - 1)
                End If

                If Left(TagName, 1) = "/" Then
                    TagName = Mid(TagName, 2)
                    SearchForBlock = False
                Else
                    SearchForBlock = True
                End If

                If InStr(1, HTMLTagList.ToString, ";" & TagName & ";", vbTextCompare) > 0 Then
                    Remove = True
                    If SearchForBlock Then
                        If InStr(1, HTMLBlockTagList.ToString, ";" & TagName & ";", vbTextCompare) > 0 Then
                            Pos2 = Len(Data)
                            Pos3 = InStr(Pos1 + 1, Data, "</" & TagName, vbTextCompare)
                            If Pos3 > 0 Then
                                Pos3 = InStr(Pos3 + 1, Data, ">")
                            End If

                            If Pos3 > 0 Then
                                Pos2 = Pos3
                            End If
                        End If
                    End If
                Else
                    Remove = False
                End If

                If Remove Then
                    Result = Result & Left(Data, Pos1 - 1)
                    Data = Mid(Data, Pos2 + 1)
                Else
                    Result = Result & Left(Data, Pos1)
                    Data = Mid(Data, Pos1 + 1)
                End If
            Else
                Result = Result & Data
                Data = ""
            End If

            Pos1 = InStr(Data, "<")
        Loop

        Result = Result & Data

        Return Result

    End Function

    Protected Sub SetViewed(ByVal ItemID As Guid, ByVal IsViewed As Boolean)
        If IsViewed = False Then
            Dim Viewed As New Views()
            Viewed.InsertPageViews(ItemID)
        End If
    End Sub

    Protected Function IsPrintMeOrPopUpActive() As Boolean
        If GetBooleanFromQueryString("printme") = True Or GetBooleanFromQueryString("popup") = True Then
            Return True
        Else
            Return False
        End If
    End Function

    Protected Function CheckLink(ByVal URLLink As String) As String

        Dim HTTPTest As Integer
        Dim HTTPLink As String

        HTTPTest = InStr(URLLink, "http")

        If HTTPTest = 0 Then
            HTTPLink = "http://" & URLLink
        Else
            HTTPLink = URLLink
        End If

        Return HTTPLink

    End Function

#End Region

#Region " Text Highlighting "

    Protected Function HighlightText(ByVal SearchWord As String, ByVal InputText As String) As String

        Dim Results As String

        If SearchWord = String.Empty Then
            Results = InputText
        Else

            Dim expression As Regex

            If HighLightSearch Then
                If HighLightExactMatch Then
                    'Match the exact instance of the characters
                    expression = New Regex("\b" + SearchWord.Replace(" ", "\b|\b").Trim + "\b", RegexOptions.IgnoreCase)
                Else
                    'Match any instance of the characters
                    expression = New Regex(SearchWord.Replace(" ", "|"), RegexOptions.IgnoreCase)
                End If

                Results = expression.Replace(InputText, AddressOf ReplaceKeywords)
            Else
                Results = InputText
            End If

        End If

        Return Results

    End Function

    Private Function ReplaceKeywords(ByVal m As Match) As String
        Return "<span class='HIGHLIGHT'>" + m.Value + "</span>"
    End Function

#End Region

#Region " Smilies "

    Protected Sub LoadSmilies(ByVal Ctl As Label, ByVal User As String, ByVal Post As String)

        Dim SB As New StringBuilder

        SB.Append(Post)

        If IsUserAuthenticated Then

            If PU.EnableSmilies(User) Then
                Ctl.Text = InsertSmilies(Post)
            Else
                Ctl.Text = Post
            End If
        Else
            Ctl.Text = InsertSmilies(Post)
        End If

    End Sub

    Private Function InsertSmilies(ByVal InputText As String) As String

        InputText = Regex.Replace(InputText.ToString, ":D", ReplaceSmiley("biggrin"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":\?", ReplaceSmiley("confused"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, "8\)", ReplaceSmiley("cool"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":\!", ReplaceSmiley("exclaim"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, "lol", ReplaceSmiley("lol"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":X", ReplaceSmiley("mad"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":\|", ReplaceSmiley("neutral"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":P", ReplaceSmiley("razz"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":\(", ReplaceSmiley("sad"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":\)", ReplaceSmiley("smile"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ":O", ReplaceSmiley("surprised"), RegexOptions.IgnoreCase)
        InputText = Regex.Replace(InputText.ToString, ";\)", ReplaceSmiley("wink"), RegexOptions.IgnoreCase)

        Return InputText.ToString

    End Function

    Private Function ReplaceSmiley(ByVal SmileyName As String) As String
        Return String.Format("<img runat=""server"" src=""App_Themes/{0}/images/smilies/{1}.gif"" border=""0""/>", Page.Theme.ToString.Trim, SmileyName)
    End Function

#End Region

#Region " Email/Messaging "

    Protected Sub SendMailUsingClient(ByVal ToAddress As String, ByVal Subject As String, ByVal Body As String)

        Response.Redirect(String.Format("mailto:{0}?Subject={1}&body={2}", ToAddress, Subject, Body))

    End Sub

    Protected Sub SendEmail(ByVal ToAddressList As String, ByVal CCAddressList As String, ByVal BCCAddressList As String, ByVal FromAddress As String, ByVal Subject As String, ByVal Body As String, ByVal IsHTMLEmail As Boolean)
        Dim EmailData As New MailUtility
        Dim ToList() As String
        Dim CCList() As String
        Dim BCCList() As String
        Dim ToName As Object
        Dim CCName As Object
        Dim BCCName As Object
        Dim credentials As New System.Net.NetworkCredential(AdminEmail, AdminEmailPassword)

        EmailData.fromAddress = FromAddress
        EmailData.subject = Subject
        EmailData.body = Body
        EmailData.isHtmlEmail = IsHTMLEmail
        EmailData.smtpServer = AppSettings("SMTPServer")
        EmailData.CreateMailObjects()

        ToList = Split(ToAddressList, ",")
        CCList = Split(CCAddressList, ",")
        BCCList = Split(BCCAddressList, ",")

        For Each ToName In ToList
            If Not String.IsNullOrEmpty(ToName) Then
                EmailData.AddToAddress(ToName.ToString.Trim)
            End If
        Next

        For Each CCName In CCList
            If Not String.IsNullOrEmpty(CCName) Then
                EmailData.AddCCAddress(CCName.ToString.Trim)
            End If
        Next

        For Each BCCName In BCCList
            If Not String.IsNullOrEmpty(BCCName) Then
                EmailData.AddBCCAddress(BCCName.ToString.Trim)
            End If
        Next

        EmailData.AuthenticateToServer(credentials)
        EmailData.SendEmail(False)

    End Sub

    Protected Sub SendPrivateMessage(ByVal ToUserID As Guid, ByVal FromUserID As Guid, ByVal MessageSubject As String, ByVal MessageBody As String)

        Try
            Dim Message As PrivateMessage = PrivateMessage.NewPrivateMessage

            Message.subject = MessageSubject
            Message.body = MessageBody
            Message.fromuserid = FromUserID
            Message.userid = ToUserID
            Message.Save()

            If EnableEmailNotifications Then
                GenerateNotificationEmails(Membership.GetUser(ToUserID).UserName.Trim())
            End If
        Catch
            'Do Nothing at this time.
        End Try

    End Sub

    Protected Sub GenerateNotificationEmails(ByVal UserName As String)
        Dim PU As New ProfileUtility

        If PU.ReceiveEmailNotification(UserName) Then

            Dim ToAddress As String = Membership.GetUser(UserName).Email
            Dim FromAddress As String = MailSettingsSection.Smtp.From.ToString().Trim()
            Dim EmailBody As New StringBuilder
            Dim Subject As String = String.Format("{0} {1}", Resources.Resource.PrivateMessageSubject, CurrentUser)

            EmailBody.Append(Resources.Resource.AutoGeneratedEmail)
            EmailBody.Append("<br>")
            EmailBody.Append(String.Format("{0} {1}", Resources.Resource.PrivateMessageBody.ToString, CurrentUser))
            EmailBody.Append("<br>")
            EmailBody.Append(String.Format("<a href=""http://{0}{1}?pid=msg_messagesystem"">{2}</a>", Request.ServerVariables("HTTP_HOST"), Request.ServerVariables("URL"), Resources.Resource.PrivateMessages))
            EmailBody.Append("<br>")
            EmailBody.Append(String.Format("<a href=""http://{0}{1}"">{2}</a>", Request.ServerVariables("HTTP_HOST"), Request.ServerVariables("URL"), SiteTitle))
            EmailBody.Append("<br>")
            EmailBody.Append("<br>")
            EmailBody.Append(String.Format("<a href=""http://{0}{1}?pid=cp_profile"">{2}</a>", Request.ServerVariables("HTTP_HOST"), Request.ServerVariables("URL"), Resources.Resource.UnsubscribeFromEmails))

            SendEmail(ToAddress, "", "", FromAddress, Subject, EmailBody.ToString().Trim(), True)
        End If

    End Sub

    'Protected Sub SendEmail(ByVal ToAddress As String, ByVal FromAddress As String, ByVal Subject As String, ByVal Body As String)
    '    Dim Smtp As New SmtpClient
    '    Dim MM As New MailMessage(FromAddress, ToAddress)

    '    Dim credentials As New System.Net.NetworkCredential(AdminEmail, AdminEmailPassword)

    '    MM.Subject = Subject
    '    MM.Body = Body
    '    MM.IsBodyHtml = True

    '    Smtp.Credentials = credentials
    '    Smtp.Host = AppSettings("SMTPServer")
    '    Smtp.Send(MM)
    'End Sub

#End Region

End Class